package com.lkz.provider.controller;

import com.lkz.provider.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class HelloController {

    private final Logger logger = LoggerFactory.getLogger(HelloController.class) ;

    @Autowired
    private DiscoveryClient client ; // 服务发现客户端

    @Autowired
    private Registration registration ; // 服务注册

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() {
        ServiceInstance instance = serviceInstance() ;
        logger.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
        return "Hello World" ;
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    @ResponseBody
    public String getName(String name){
        logger.info("name=" + name);
        return name ;
    }

    @RequestMapping(value = "/po", method = RequestMethod.GET)
    @ResponseBody
    public User getUser(User user) {
        logger.info("name = " + user.getName());
        return user ;
    }

    @RequestMapping(value = "/puser", method = RequestMethod.POST)
    @ResponseBody
    public String getPName(String name){
        logger.info("name = " + name);
        return name ;
    }

    public ServiceInstance serviceInstance() {
        List<ServiceInstance> clientList = client.getInstances(registration.getServiceId()) ;
        if(clientList != null && clientList.size() > 0){
            for (ServiceInstance itm : clientList){
                if(itm.getPort() == 8080 || itm.getPort() == 8081){
                    return itm ;
                }
            }
        }
        return null ;
    }


}
